// ProjectName: go-learn-demo
// PackageName: elasticybxb
// Description: 低级API操作文档
// Author: hy.bai
// Date: 2025-09-01 星期一 18:34

package elasticybxb

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log/slog"
	"strings"
)

var LowDocument lowDocument

type lowDocument struct {
}

// 创建文档
func (*lowDocument) ElasticCreateDoc() {
	client, _ := LowInitElastic.InitElasticByUsername()
	book := &Book{
		1,
		"go语言程序设计",
		"hy.bai",
		100,
	}
	data, _ := json.Marshal(book)

	// 低级API的方式创建文档
	resp, err := client.Index(LOW_DOC_NAME, bytes.NewReader(data))
	if err != nil {
		slog.Error(fmt.Sprintf("Elastic Create Index Error: %s", err.Error()))
		return
	}
	slog.Info(fmt.Sprintf("Elastic Create Index: %s", resp.String()))
}

// 带Id的创建文档
func (*lowDocument) ElasticCreateDocWithId() {
	client, _ := LowInitElastic.InitElasticByUsername()
	book := &Book{
		1,
		"go语言程序设计",
		"hy.bai",
		100,
	}
	data, _ := json.Marshal(book)
	// 低级API的方式创建文档
	// 带上自定义的ID
	resp, err := client.Index(LOW_DOC_NAME_WITH_ID, bytes.NewReader(data), client.Index.WithDocumentID("1"))
	if err != nil {
		slog.Error(fmt.Sprintf("Elastic Create Index Error: %s", err.Error()))
		return
	}
	slog.Info(fmt.Sprintf("Elastic Create Index: %s", resp.String()))
}

// 批量创建文档
func (*lowDocument) ElasticCreateDocBatch() {
	client, _ := LowInitElastic.InitElasticByUsername()
	buffer := bytes.NewBufferString(`
		{"index":{"_id":"9780553351927"}}
		{"name":"Snow Crash","author":"Neal Stephenson","release_date":"2025-06-01","page_count": 470}
		{"index":{"_id":"9780441017225"}}
		{"name":"Revelation","author":"Alastair Reynol","release_date":"2000-03-15","page_count": 585}
	`)
	// 添加换行符
	buffer.WriteByte('\n')
	resp, err := client.Bulk(bytes.NewReader(buffer.Bytes()), client.Bulk.WithIndex(LOW_DOC_NAME_BATCH))
	if err != nil {
		slog.Error("批量创建文档失败,原因是:", err.Error())
		return
	}
	fmt.Println(resp)
}

// 通过查询条件删除
func (*lowDocument) ElasticDeleteDocByCondition() {
	client, _ := LowInitElastic.InitElasticByUsername()
	q := `
		{
			"query": {
				"match": {
					"name": "Revelation"
				}
			}
		}
	`
	resp, err := client.DeleteByQuery([]string{LOW_DOC_NAME_BATCH}, strings.NewReader(q))
	if err != nil {
		slog.Error("删除文档失败,原因是:", err.Error())
	}
	// 操作结果
	fmt.Println(resp)
}

func TestLowElasticDoc() {
	LowDocument.ElasticDeleteDocByCondition()
}
